<template>
    <!-- 经办人-流程记录（处理中加流程表单审批建议、驳回通过按钮） -->
    <wd-popup v-model="visible" position="bottom" v-if="isInApprove && isAssigneeUser">   
        <view class="steps-pd">
            <wd-steps :active="processInstanceTaskList.length" vertical dot  v-if="isAssigneeUser" >
                <wd-step v-if="startData.endTime" :title="` 结束流程:在${ dayjs(startData.endTime).format('YYYY-MM-DD HH:mm:ss') }结束`" />
                <wd-step v-for="_ in processInstanceTaskList" :key="_.id" :title="`审批任务：${_.name}`" >
                    <template #description>
       
                        <view class="timeline-item-label">
                          <div class="item">
                            <div class="title">审批人：</div>
                            <div class="content">{{ _.assigneeUser?.nickname }} <t-tag>{{ _.assigneeUser?.deptName }}</t-tag></div>
                          </div>
                          <div class="item">
                            <div class="title">创建时间：</div>
                            <div class="content color-gray">{{ dayjs(_.createTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                          </div>
                          <div v-if="_.endTime" class="item">
                            <div class="title">审批时间：</div>
                            <div class="content color-gray">{{ dayjs(_.endTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                          </div>
                      
                          <div v-if="_.durationInMillis" class="item">
                            <div class="title">耗时：</div>
                            <div class="content color-gray">{{ (_.durationInMillis / 1000 / 60).toFixed(1) }}分钟</div>
                          </div>
                          <div class="item">
                            <div class="title">审批备注：</div>
                            <div class="content">{{ _.reason }}</div>
                          </div>
                        </view>
   
                    </template>
                </wd-step>
                <wd-step :title="`发起流程:【${startData.userName}】在${ dayjs(startData.startTime).format('YYYY-MM-DD HH:mm:ss') }发起【${startData.processName}】流程`" />
            </wd-steps>
        </view>	
		<wd-form ref="formRef" :model="formData">
			<wd-cell-group border>
                <wd-cell  
                    v-if="approveData.reason"
                    title="备注" 
                    >
					<view class="content"> 
						{{ approveData.reason  }}
					</view>
				</wd-cell>
                 <wd-cell  
                    v-if="approveData.fileUrl"
                    title="延期图片" 
                    >
					<view class="content"> 
						<template v-for="(file, index) in approveData.fileUrl" :key="index">
          		          <file-preview :file="file" />
          		        </template>
					</view>
				</wd-cell>
                <wd-datetime-picker 
                  v-if="isInApprove && isAssigneeUser && ['1'].includes(props.approveType)"
				  type="date" 
				  v-model="formData.delayTime" 
				  prop="delayTime" 
				  :rules="[
				    { required: true, message: '请选择审批时间' },
				    
				  ]" 
				  label="审批时间" 
				  @confirm="handleConfirm" 
				/>
				<wd-textarea
                    v-if="isInApprove && isAssigneeUser"
                    v-model="formData.reason" 
                    prop="reason" 
                    label="审批意见" 
                    auto-height 
                    placeholder="请输入审批意见"
					clearable
                    :rules="[{required:true,message:'请输入审批意见'}]"  
                />
				
			</wd-cell-group>
            <view class="footer">
              <wd-button type="primary" @click="handlePassApprove">通过</wd-button>
              <wd-button type="warning" @click="handleRejectApprove">驳回</wd-button>
            </view>
		</wd-form>
        
  </wd-popup>
</template>

<script setup>
import dayjs from 'dayjs';
import { ref,watch,computed } from 'vue';

import {
	useUserStore
} from '@/store/index.js'

import {
  applyAbandonedOrder,
  getOAExamine,
  getProcessInstance,
  getProcessInstanceIdByOrderIdAndType,
  getProcessInstanceTaskList,
  passApprove,
  rejectApprove,
  transformDesignExtension,
} from '@/api/approve/approve.js';
import FilePreview from '../file-preview/file-preview.vue';
// 用户仓库
const userStore = useUserStore()

const props = defineProps({
  orderId: {
    type: Number,
    required: true
  },
  approveType: {
    type: String,
    required: true
  }
})

// 显示
const visible = ref(true);
// 表单ref
// const formRef = useTemplateRef<typeof Form>('formRef');
// 表单数据
const formData = ref({});
// 审批数据
const approveData = ref({});
// 发起流程-结束流程
const startData = ref({})
// 是否正在审批--审批人
const isInApprove = computed(() => {
  return approveData.value.status === 1;
});
// 是否正在审批--订单
const isInApproveOrder = computed(() => {
  return approveData.value.designStatus === 1;
});
// 是否审批用户
const isAssigneeUser = computed(() => {
  console.log('isAssigneeUser', approveData.value.assigneeUserId, userStore.userInfo.id);
  return approveData.value.assigneeUserId === userStore.userInfo.id;
});
// 是发起审批用户
const isInitialUser = computed(() => {
  console.log('isInitialUser', approveData.value.assigneeUserId, userStore.userInfo.id);
  return startData.value.userId === userStore.userInfo.id;
});
// 是否展示发起审核表单
const shouldShowInitiateApproval = computed(() => {
  // 条件 1：没有审批流程或 designStatus 为 3（驳回）
  const isCondition1True = !(isInApproveOrder.value && processInstanceTaskList.value.length) || approveData.value.designStatus === 3 || approveData.value.designStatus === 4;

  // 条件 2：approveType 为 2 或 4
  const isCondition2True = ['2', '4'].includes(props.approveType);

  // 同时满足条件 1 和条件 2
  return isCondition1True && isCondition2True;
});
// 处理获取流程实例
const handleGetProcessInstance = (id) => {
  const params = {
    id,
  };
  return getProcessInstance(params)
    .then((data) => {
      console.log('handleGetProcessInstance', data);
      approveData.value.designStatus = data.status;
      Object.keys(data.formVariables).forEach((key) => {
        approveData.value[key] = data.formVariables[key];
      });
      startData.value.endTime = data.endTime
      startData.value.startTime = data.startTime
      startData.value.processName = data.name
      if(data.startUser) {
        startData.value.userName = data.startUser.nickname
        startData.value.userId = data.startUser.id
      }
      startData.value.businessKey = data.businessKey
      
    })
   .catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		})
};
// 处理获取备注
const handleGetRemark = (id) => {
  const params = {
    id,
  };
  return getOAExamine(params)
    .then((data) => {
      console.log('handleGetRemark', data);
      approveData.value.reason = data.reason;
      approveData.value.fileUrl = data.fileUrl;
      
    })
   .catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		})
};
// 流程实例任务列表
const processInstanceTaskList = ref([]);
// 处理获取流程实例任务列表
const handleGetProcessInstanceTaskList = (processInstanceId) => {
  const params = {
    processInstanceId,
  };
  return getProcessInstanceTaskList(params)
    .then((data) => {
      processInstanceTaskList.value = data;
      data.forEach((item) => {
        if (item.assigneeUser?.id === userStore.userInfo.id) {
          approveData.value.taskId = item.id;
          approveData.value.assigneeUserId = item.assigneeUser.id;
          approveData.value.status = item.status;
        }
      });
      console.log(approveData,'llll');
      startData.value.status = data[0].status

      // approveData.value.taskId = data[0].id;
      // approveData.value.assigneeUserId = data[0].assigneeUser.id;
    })
    .catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		})
};
// 处理通过审批
const handlePassApprove = async () => {
  const validateResult = await formRef.value.validate();
  if (validateResult !== true) return;
//   loadingSubmit.value = true;
  const params = {
    id: approveData.value.taskId,
    reason: formData.value.reason,
    delayTime: formData.value.delayTime,
  };
  passApprove(params)
    .then(() => {
      MessagePlugin.success('操作成功');
      emits('requestSuccess', { mode: 'update' });
      // handleGetApproveData();
      visible.value = false;
    })
    .catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		})
    .finally(() => {
    //   loadingSubmit.value = false;
    });
};
// 处理拒绝审批
const handleRejectApprove = async () => {
  const validateResult = await formRef.value.validate();
  if (validateResult !== true) return;
//   loadingSubmit.value = true;
  const params = {
    id: approveData.value.taskId,
    reason: formData.value.reason,
  };
  rejectApprove(params)
    .then(() => {
      MessagePlugin.success('操作成功');
      emits('requestSuccess', { mode: 'update' });
      // handleGetApproveData();
      visible.value = false;
    })
   .catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		})
    .finally(() => {
    //   loadingSubmit.value = false;
    });
};
// 加载骨架屏
const loadingSkeleton = ref(false);
// 处理获取审批数据
const handleGetApproveData = async () => {
  formData.value = {};
//   loadingSkeleton.value = true;
  const params = {
    orderId: props.orderId,
    type: props.approveType,
  };
  try {
    const data = await getProcessInstanceIdByOrderIdAndType(params);
    const processInstanceId = data[0];
    console.log(processInstanceId,'processInstanceId');
    
    if (processInstanceId) {
      console.log(data);
      await handleGetProcessInstance(processInstanceId);
      await handleGetProcessInstanceTaskList(processInstanceId);
      if(startData.value.businessKey) {
        await handleGetRemark(startData.value.businessKey)
      }
    }
  } catch (error) {
     uni.showToast({
      title: error || '获取数据失败',
      icon: 'error'
    })
  } finally {
    // loadingSkeleton.value = false;
  }
};
const handleConfirm = ({ value, prop }) => {
  if (value) {
    formData[prop] = dayjs(value).format('YYYY-MM-DD 23:59:59');
  } else {
    formData[prop] = undefined;
  }
};
// 打开
const open = () => {
  console.log('open() called'); // 调试
  handleGetApproveData();
  visible.value = true;
};
// 关闭
const close = () => {
  visible.value = false;
};

defineExpose({
  open,
  close,
});
</script>
<style lang="scss" scoped>
.steps-pd {
    padding: 14px;
}
.timeline-item-label {
  margin-top: 6px;

  .item {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .title {
      width: 70px;
      text-align: justify;
      text-align-last: justify;
      flex-shrink: 0;
    }
    .content {
      max-width: 500px;
    }
    .color-gray {
      color: gray;
    }
  }
  
}
.footer {
    display: flex;
}
</style>